import type { PQRequest } from '@prequest/types'
import type { ActionFn } from '../interceptorActionHandler'
import qs from 'qs'
import { isObject } from 'lodash'

/**
 * 清除对象内部的无效参数
 * @param {object} paramsObj 对象
 * @return {object} 处理后对象
 */
function removeInvalidParams (paramsObj: object) {
  const data = Object.entries(paramsObj).reduce((obj, item) => {
    const [key, value] = item
    if (value !== undefined && value !== '' && value !== 'undefined') {
      return { ...obj, [key]: value }
    } else {
      return obj
    }
  }, {})
  return data
}

/**
 * 请求参数处理器
 * @description 1.去除无效参数
 * @param {object} request 请求上下文
 * @return {object}
 */
export const paramsHandler: ActionFn = (request: PQRequest) => {
  const handler = () => {
    const [path, pathParams] = request.path.split('?')
    if (pathParams) {
      const pathParamsObj = qs.parse(pathParams)
      if (isObject(pathParamsObj)) {
        const newParams = qs.stringify(removeInvalidParams(pathParamsObj), { addQueryPrefix: true })
        request.path = path + newParams
      }
    }

    if (isObject(request.data)) {
      request.data = removeInvalidParams(request.data)
    }
    return request
  }

  return { checkHandle: true, value: handler }
}
